﻿using System;
using CoreTypes;
using System.Custom;
using System.Drawing;
using System.Globalization;
using System.Custom.Window;
using System.Windows.Forms;
using System.ComponentModel;
using MainModule.Properties;

namespace MainModule
{
   public partial class AccountProperties : Window
   {
      #region Window Data

      Account FAccount;
      Font FFontB, FFontU;
      bool FAssigningPrivacy;
      AccountSettings FSettings;
      InternetCommunicator FCommunicator = InternetCommunicator.Self;
      string FDefaultPassword = "******************************************";

      #endregion

      public AccountProperties()
      {
         InitializeComponent();

         ColorTheme = FCommunicator.ColorTheme;
         RenderMode = FCommunicator.RenderMode;

         FFontB = new Font(richTextBoxSummary.Font, FontStyle.Bold);
         FFontU = new Font(richTextBoxSummary.Font, FontStyle.Underline);

         FCommunicator.PropertyChanged += communicator_PropertyChanged;
         FCommunicator.LoadAccountDataState += communicator_LoadAccountDataState;
         FCommunicator.SaveAccountDataState += communicator_SaveAccountDataState;
         FCommunicator.RequestUserInfoState += communicator_RequestUserInfoState;

         panelPasswordSettings.Height -= panelPasswordSettingsChangePassword.Height;
         panelPasswordSettings.MaximumSize = new Size(0, panelPasswordSettings.Height);

         dataTablePolicyValues.Rows.Add(PolicyRule.None, Resources.S_Use_common_settings);
         dataTablePolicyValues.Rows.Add(PolicyRule.Allow, Resources.S_Start_session);
         dataTablePolicyValues.Rows.Add(PolicyRule.Ask, Resources.S_Ask_me);
         dataTablePolicyValues.Rows.Add(PolicyRule.Block, Resources.S_Block);
         dataTablePolicyValues.Rows.Add(PolicyRule.Ignore, Resources.S_Ignore);

         dataTablePrivacyValues.Rows.Add(PrivacyRule.Anyone, Resources.S_Anyone);
         dataTablePrivacyValues.Rows.Add(PrivacyRule.MyContats, Resources.S_My_contats_only);
         dataTablePrivacyValues.Rows.Add(PrivacyRule.VipContacts, Resources.S_Vip_contacts_only);
         dataTablePrivacyValues.Rows.Add(PrivacyRule.Nobody, Resources.S_Nobody);

         dataTableStatusValues.Rows.Add(StatusCodes.Online, Resources.S_Online);
         dataTableStatusValues.Rows.Add(StatusCodes.SeemsAway, Resources.S_Away);
         dataTableStatusValues.Rows.Add(StatusCodes.NotAvailable, Resources.S_Not_available);
         dataTableStatusValues.Rows.Add(StatusCodes.Invisible, Resources.S_Invisible);
         dataTableStatusValues.Rows.Add(StatusCodes.Phantom, Resources.S_Phantom);

         comboBoxCountry.Items.Add("");
         comboBoxCountry.Items.AddRange(Cultures.Countries);
         comboBoxWorkCountry.Items.Add("");
         comboBoxWorkCountry.Items.AddRange(Cultures.Countries);

         linkPrivacyDetails_Click(this, null);

         window_AeroGlassEffectChanged(null, null);
      }

      protected override void Dispose(bool disposing)
      {
         FCommunicator.PropertyChanged -= communicator_PropertyChanged;
         FCommunicator.LoadAccountDataState -= communicator_LoadAccountDataState;
         FCommunicator.SaveAccountDataState -= communicator_SaveAccountDataState;
         FCommunicator.RequestUserInfoState -= communicator_RequestUserInfoState;

         if (disposing && (components != null))
         {
            components.Dispose();
         }
         base.Dispose(disposing);
      }

      public override ColorTheme ColorTheme
      {
         get
         {
            return base.ColorTheme;
         }
         set
         {
            base.ColorTheme = value;
            Refresh();
         }
      }

      public void Show(Account user, string page)
      {
         AssignUser(user);

         ControlEffects.Slide(panelWorkInfo, SlideAction.Collapse, false);
         ControlEffects.Slide(panelMiscInfo, SlideAction.Collapse, false);
         ControlEffects.Slide(panelPasswordSettings, SlideAction.Collapse, false);

         if (page == null) page = "";

         string subPage = page.SubstrAfter("/");
         page = page.SubstrBefore("/");

         tabControl.SelectedTab = tabControl.TabPages.ContainsKey("tabPage" + page) ?
                                    tabControl.TabPages["tabPage" + page] :
                                    tabControl.TabPages["tabPageSummary"];
         
         tabControl_SelectedIndexChanged(this, null);
         checkBoxOverrideCommonPrivacy_CheckedChanged(this, null);

         if (page == "Privacy")
         {
            if (subPage == "Password")
            {
               ControlEffects.Slide(panelContactsPolicy, SlideAction.Collapse, false);
               ControlEffects.Slide(panelPasswordSettings, SlideAction.Expand, false);
               buttonChangePassword_Click(this, null);
            }
            else
            {
               ControlEffects.Slide(panelPasswordSettings, SlideAction.Collapse, false);
            }
         }

         Size = MinimumSize;
         CenterToScreen();
         Visualize();
      }
      public override void Translate(CultureInfo culture)
      {
         base.Translate(culture);
         UpdatewWindowView();
      }

      private bool Save()
      {
         try
         {
            if (tabControl.SelectedTab == tabPageInfo)
            {
               FAccount.CustomName = textBoxCustomName.Text;
               FAccount.Nickname = textBoxNickname.Text;

               FAccount.Info.Email = textBoxEmail.Text;
               FAccount.Info.Phone = textBoxPhone.Text;
               FAccount.Info.City = textBoxCity.Text;
               FAccount.Info.Country = comboBoxCountry.Text;
               FAccount.Info.PersonalUrl = textBoxUrl.Text;
               FAccount.Info.FullName = textBoxFullName.Text;
               FAccount.Info.Description = textBoxAbout.Text;
               FAccount.Info.Language = comboBoxLanguage.SelectedText;
               FAccount.Info.Gender = comboBoxGender.SelectedIndex > 0 ? (int?)(comboBoxGender.SelectedItem.ToString() == UserInfo.GetGenderAsString(1, true) ? 1 : 0) : null;

               FAccount.Info.Work.City = textBoxWorkCity.Text;
               FAccount.Info.Work.Address = textBoxWorkAddress.Text;
               FAccount.Info.Work.Country = comboBoxWorkCountry.Text;
               FAccount.Info.Work.Department = textBoxDepartment.Text;
               FAccount.Info.Work.Organization = textBoxOrganization.Text;
               FAccount.Info.Work.Phone = textBoxWorkPhone.Text;
               FAccount.Info.Work.Fax = textBoxFax.Text;
               FAccount.Info.Work.Url = textBoxWorkUrl.Text;
               FAccount.Info.Work.Email = textBoxWorkEmail.Text;
               FAccount.Info.Work.Role = textBoxRole.Text;

               int year = 0, month = 0, day = 0;
               if (comboBoxYear.Text != "") year = Convert.ToInt16(comboBoxYear.Text);

               if (comboBoxDay.SelectedIndex < 0) comboBoxDay.SelectedIndex = 0;
               if (comboBoxMonth.SelectedIndex < 0) comboBoxMonth.SelectedIndex = 0;

               string birthday = year + "." + comboBoxMonth.SelectedIndex + "." + comboBoxDay.SelectedIndex;

               if (UserInfo.ParseBirthday(birthday, out year, out month, out day)) { FAccount.Info.Birthday = birthday; }
               else { FCommunicator.ShowError(Resources.S_Invalid_date_format_entered, null); comboBoxYear.Focus(); return false; }

               FCommunicator.SaveAccountData(FAccount, SaveAccountActions.SaveInfo);
            }
            else
            {
               FAccount.AutoLogon = checkBoxAutoLogon.Checked;
               FAccount.RememberPassword = checkBoxRememberPassword.Checked;
               if (FAccount.RememberPassword && textBoxPassword.Text != "" && textBoxPassword.Text != FDefaultPassword) FAccount.Password = textBoxPassword.Text;

               FSettings.StartupStatus = (StatusCodes)Enum.Parse(typeof(StatusCodes), (string)comboBoxStartupStatus.SelectedValue);

               if (checkBoxLogonDelay.Checked && comboBoxLogonDelay.Text != "")
               {
                  try { FSettings.LogonDelay = Convert.ToInt16(comboBoxLogonDelay.Text); }
                  catch { FCommunicator.ShowError(Resources.S_Invalid_number_format.Replace("<field>", Resources.S_Logon_delay), null); comboBoxLogonDelay.Focus(); return false; }
               }
               else FSettings.LogonDelay = 0;

               if (checkBoxAwayTimeout.Checked && comboBoxAwayTimeout.Text != "")
               {
                  try { FSettings.AwayTimeout = Convert.ToInt16(comboBoxAwayTimeout.Text); }
                  catch { FCommunicator.ShowError(Resources.S_Invalid_number_format.Replace("<field>", Resources.S_Away_timeout), null); comboBoxAwayTimeout.Focus(); return false; }
               }
               else FSettings.AwayTimeout = 0;

               if (FSettings.AwayTimeout == Settings.Default.AwayTimeout) FSettings.AwayTimeout = -1;

               if (checkBoxNaTimeout.Checked && comboBoxNaTimeout.Text != "")
               {
                  try { FSettings.NATimeout = Convert.ToInt16(comboBoxNaTimeout.Text); }
                  catch { FCommunicator.ShowError(Resources.S_Invalid_number_format.Replace("<field>", Resources.S_Not_available_timeout), null); comboBoxNaTimeout.Focus(); return false; }
               }
               else FSettings.NATimeout = 0;

               if (FSettings.NATimeout == Settings.Default.NATimeout) FSettings.NATimeout = -1;

               if (!checkBoxOverrideCommonPrivacy.Checked)
               {
                  FSettings.UnknownUserMessageRule = PolicyRule.None;
                  FSettings.UnknownUserInvitationRule = PolicyRule.None;
                  FSettings.MyContactMessageRule = PolicyRule.None;
                  FSettings.MyContactInvitationRule = PolicyRule.None;
                  FSettings.VipContactInvitationRule = PolicyRule.None;
               }

               FAccount.Settings = FSettings;

               FCommunicator.SaveAccountData(FAccount, SaveAccountActions.SaveSettings);
            }

            if (FCommunicator.SaveProfile(null, false))
            {
               panelSaving.Visible = true;
               DelayedAction.Do(() => panelSaving.Visible = false, 500);
               return true;
            }
            else return false;
         }
         catch (Exception error)
         {
            FCommunicator.ShowError(Resources.S_Unhandled_error_occured, error);

            return false;
         }
      }
      private void SetupUserpic()
      {
         buttonZoom.Visible = false;

         Image pic = FAccount.Info.Userpic;

         try
         {
            if (pictureBox1.Image != null) pictureBox1.Image.Dispose();
            if (pictureBox2.Image != null) pictureBox2.Image.Dispose();

            if (pic == null)
            {
               pictureBox1.Image = pictureBox2.Image = FCommunicator.DefaultUserpic;
               pictureBox1.SizeMode = pictureBox2.SizeMode = PictureBoxSizeMode.StretchImage;
            }
            else
            {
               pictureBox1.Image = pictureBox2.Image = pic;

               if (pic.Width == pictureBox1.Width && pic.Height == pictureBox1.Height)
               {
                  pictureBox1.SizeMode = pictureBox2.SizeMode = PictureBoxSizeMode.Normal;
               }
               else if (pic.Width > pictureBox1.Width || pic.Height > pictureBox1.Height)
               {
                  buttonZoom.Visible = true;
                  pictureBox1.SizeMode = pictureBox2.SizeMode = PictureBoxSizeMode.Zoom;
               }
               else
               {
                  pictureBox1.SizeMode = pictureBox2.SizeMode = PictureBoxSizeMode.CenterImage;
               }
            }
         }
         catch (Exception error)
         {
            FCommunicator.ShowError(Resources.S_Unable_to_show_picture, error);
         }
      }
      private void AssignPrivacy()
      {
         FAssigningPrivacy = true;

         try
         {
            checkBoxMessageRuleBlock.Checked = FSettings.UnknownUserMessageRule == PolicyRule.Block;
            checkBoxInvitationRuleBlock.Checked = FSettings.UnknownUserInvitationRule == PolicyRule.Block;
            
            comboBoxUnknownUserMessageRule.SelectedValue = FSettings.UnknownUserMessageRule;
            comboBoxUnknownUserInvitationRule.SelectedValue = FSettings.UnknownUserInvitationRule;
            
            comboBoxMyContactsMessageRule.SelectedValue = FSettings.MyContactMessageRule;
            comboBoxMyContactsInvitationRule.SelectedValue = FSettings.MyContactInvitationRule;
            comboBoxVipInvitationRule.SelectedValue = FSettings.VipContactInvitationRule;
         }
         finally
         {
            FAssigningPrivacy = false;
         }
      }
      private void AssignCapabilities()
      {
         //-----------------------------------------
         textBoxNickname.ReadOnly = !FAccount.ServiceConfig.SupportsSettingOf(ServiceFields.Nickname);
         textBoxNickname.Enabled = FAccount.ServiceConfig.SupportsGettingOf(ServiceFields.Nickname) ||
                                   FAccount.ServiceConfig.SupportsSettingOf(ServiceFields.Nickname);
         labelNickname.Enabled = !textBoxNickname.ReadOnly;
         //-----------------------------------------
         textBoxEmail.ReadOnly = !FAccount.ServiceConfig.SupportsSettingOf(ServiceFields.Email);
         textBoxEmail.Enabled = FAccount.ServiceConfig.SupportsGettingOf(ServiceFields.Email) ||
                                FAccount.ServiceConfig.SupportsSettingOf(ServiceFields.Email);
         labelEmail.Enabled = !textBoxEmail.ReadOnly;
         //-----------------------------------------
         textBoxFullName.ReadOnly = !FAccount.ServiceConfig.SupportsSettingOf(ServiceFields.FullName);
         textBoxFullName.Enabled = FAccount.ServiceConfig.SupportsGettingOf(ServiceFields.FullName) ||
                                   FAccount.ServiceConfig.SupportsSettingOf(ServiceFields.FullName);
         labelFullName.Enabled = !textBoxFullName.ReadOnly;
         //-----------------------------------------
         textBoxCity.ReadOnly = !FAccount.ServiceConfig.SupportsSettingOf(ServiceFields.City);
         textBoxCity.Enabled = FAccount.ServiceConfig.SupportsGettingOf(ServiceFields.City) ||
                               FAccount.ServiceConfig.SupportsSettingOf(ServiceFields.City);
         labelCity.Enabled = !textBoxCity.ReadOnly;
         //-----------------------------------------
         textBoxPhone.ReadOnly = !FAccount.ServiceConfig.SupportsSettingOf(ServiceFields.CellPhone);
         textBoxPhone.Enabled = FAccount.ServiceConfig.SupportsGettingOf(ServiceFields.CellPhone) ||
                                FAccount.ServiceConfig.SupportsSettingOf(ServiceFields.CellPhone);
         labelPhone.Enabled = !textBoxPhone.ReadOnly;
         //-----------------------------------------
         textBoxFax.ReadOnly = !FAccount.ServiceConfig.SupportsSettingOf(ServiceFields.Fax);
         textBoxFax.Enabled = FAccount.ServiceConfig.SupportsGettingOf(ServiceFields.Fax) ||
                              FAccount.ServiceConfig.SupportsSettingOf(ServiceFields.Fax);
         labelFax.Enabled = !textBoxFax.ReadOnly;
         //-----------------------------------------
         textBoxAbout.ReadOnly = !FAccount.ServiceConfig.SupportsSettingOf(ServiceFields.Description);
         groupBoxAbout.Enabled = FAccount.ServiceConfig.SupportsGettingOf(ServiceFields.Description) ||
                                 FAccount.ServiceConfig.SupportsSettingOf(ServiceFields.Description);
         //-----------------------------------------
         textBoxOrganization.ReadOnly = !FAccount.ServiceConfig.SupportsSettingOf(ServiceFields.Organization);
         textBoxOrganization.Enabled = FAccount.ServiceConfig.SupportsGettingOf(ServiceFields.Organization) ||
                                       FAccount.ServiceConfig.SupportsSettingOf(ServiceFields.Organization);
         labelOrganization.Enabled = !textBoxOrganization.ReadOnly;
         //-----------------------------------------
         textBoxDepartment.ReadOnly = !FAccount.ServiceConfig.SupportsSettingOf(ServiceFields.Department);
         textBoxDepartment.Enabled = FAccount.ServiceConfig.SupportsGettingOf(ServiceFields.Department) ||
                                     FAccount.ServiceConfig.SupportsSettingOf(ServiceFields.Department);
         labelDepartment.Enabled = !textBoxDepartment.ReadOnly;
         //-----------------------------------------
         textBoxRole.ReadOnly = !FAccount.ServiceConfig.SupportsSettingOf(ServiceFields.Role);
         textBoxRole.Enabled = FAccount.ServiceConfig.SupportsGettingOf(ServiceFields.Role) ||
                               FAccount.ServiceConfig.SupportsSettingOf(ServiceFields.Role);
         labelRole.Enabled = !textBoxRole.ReadOnly;
         //-----------------------------------------
         textBoxUrl.ReadOnly = !FAccount.ServiceConfig.SupportsSettingOf(ServiceFields.PersonalUrl);
         textBoxUrl.Enabled = FAccount.ServiceConfig.SupportsGettingOf(ServiceFields.PersonalUrl) ||
                              FAccount.ServiceConfig.SupportsSettingOf(ServiceFields.PersonalUrl);
         labelUrl.Enabled = !textBoxUrl.ReadOnly;
         //-----------------------------------------
         textBoxWorkAddress.ReadOnly = !FAccount.ServiceConfig.SupportsSettingOf(ServiceFields.WorkAddress);
         textBoxWorkAddress.Enabled = FAccount.ServiceConfig.SupportsGettingOf(ServiceFields.WorkAddress) ||
                                      FAccount.ServiceConfig.SupportsSettingOf(ServiceFields.WorkAddress);
         labelWorkAddress.Enabled = !textBoxWorkAddress.ReadOnly;
         //-----------------------------------------
         textBoxWorkCity.ReadOnly = !FAccount.ServiceConfig.SupportsSettingOf(ServiceFields.WorkCity);
         textBoxWorkCity.Enabled = FAccount.ServiceConfig.SupportsGettingOf(ServiceFields.WorkCity) ||
                                   FAccount.ServiceConfig.SupportsSettingOf(ServiceFields.WorkCity);
         labelWorkCity.Enabled = !textBoxWorkCity.ReadOnly;
         //-----------------------------------------
         textBoxWorkEmail.ReadOnly = !FAccount.ServiceConfig.SupportsSettingOf(ServiceFields.WorkEmail);
         textBoxWorkEmail.Enabled = FAccount.ServiceConfig.SupportsGettingOf(ServiceFields.WorkEmail) ||
                                    FAccount.ServiceConfig.SupportsSettingOf(ServiceFields.WorkEmail);
         labelWorkEmail.Enabled = !textBoxWorkEmail.ReadOnly;
         //-----------------------------------------
         textBoxWorkPhone.ReadOnly = !FAccount.ServiceConfig.SupportsSettingOf(ServiceFields.WorkPhone);
         textBoxWorkPhone.Enabled = FAccount.ServiceConfig.SupportsGettingOf(ServiceFields.WorkPhone) ||
                                    FAccount.ServiceConfig.SupportsSettingOf(ServiceFields.WorkPhone);
         labelWorkPhone.Enabled = !textBoxWorkPhone.ReadOnly;
         //-----------------------------------------
         textBoxWorkUrl.ReadOnly = !FAccount.ServiceConfig.SupportsSettingOf(ServiceFields.WorkUrl);
         textBoxWorkUrl.Enabled = FAccount.ServiceConfig.SupportsGettingOf(ServiceFields.WorkUrl) ||
                                  FAccount.ServiceConfig.SupportsSettingOf(ServiceFields.WorkUrl);
         labelWorkUrl.Enabled = !textBoxWorkUrl.ReadOnly;
         //-----------------------------------------
         comboBoxWorkCountry.Enabled = FAccount.ServiceConfig.SupportsSettingOf(ServiceFields.WorkCountry);
         labelWorkCountry.Enabled = FAccount.ServiceConfig.SupportsSettingOf(ServiceFields.WorkCountry);
         if (!comboBoxWorkCountry.Enabled) comboBoxWorkCountry.SelectedIndex = -1;
         //-----------------------------------------
         comboBoxCountry.Enabled = FAccount.ServiceConfig.SupportsSettingOf(ServiceFields.Country);
         labelCountry.Enabled = FAccount.ServiceConfig.SupportsSettingOf(ServiceFields.Country);
         if (!comboBoxCountry.Enabled) comboBoxCountry.SelectedIndex = -1;
         //-----------------------------------------
         comboBoxLanguage.Enabled = FAccount.ServiceConfig.SupportsGettingOf(ServiceFields.Language) ||
                                    FAccount.ServiceConfig.SupportsSettingOf(ServiceFields.Language);
         labelLanguage.Enabled = FAccount.ServiceConfig.SupportsSettingOf(ServiceFields.Language);
         if (!comboBoxLanguage.Enabled) comboBoxLanguage.SelectedIndex = -1;
         //-----------------------------------------
         comboBoxDay.Enabled = FAccount.ServiceConfig.SupportsGettingOf(ServiceFields.Birthday) ||
                               FAccount.ServiceConfig.SupportsSettingOf(ServiceFields.Birthday);
         comboBoxMonth.Enabled = comboBoxYear.Enabled = comboBoxDay.Enabled;
         labelBirthday.Enabled = FAccount.ServiceConfig.SupportsSettingOf(ServiceFields.Birthday);
         if (!comboBoxDay.Enabled) comboBoxDay.SelectedIndex = comboBoxMonth.SelectedIndex = comboBoxYear.SelectedIndex = -1;
         //-----------------------------------------
         comboBoxGender.Enabled = FAccount.ServiceConfig.SupportsGettingOf(ServiceFields.Gender) ||
                                  FAccount.ServiceConfig.SupportsSettingOf(ServiceFields.Gender);
         labelGender.Enabled = FAccount.ServiceConfig.SupportsSettingOf(ServiceFields.Gender);
         if (!comboBoxGender.Enabled) comboBoxGender.SelectedIndex = -1;
         //-----------------------------------------
         panelPasswordSettings.Visible = !FAccount.ServiceConfig.AuthCurrentUser;
         buttonChangePassword.Enabled = FAccount.ServiceConfig.SupportsAction(ServiceActions.PASSWORD);
         //-----------------------------------------
         pictureBox1.Enabled = FAccount.ServiceConfig.SupportsSettingOf(ServiceFields.Userpic);
         pictureBox1.Visible = FAccount.ServiceConfig.SupportsGettingOf(ServiceFields.Userpic);
         //pictureBox2.Enabled = FAccount.Configuration.SupportsSettingOf(ServiceFields.Userpic);
         //pictureBox2.Visible = FAccount.Configuration.SupportsGettingOf(ServiceFields.Userpic);
         buttonResetUserpic.Visible = pictureBox1.Enabled;
         //-----------------------------------------
      }
      protected override void UpdatewWindowView()
      {
         AssignUser(FAccount);
         linkPrivacyDetails_Click(null, null);
      }
      private void AssignUser(Account user)
      {
         Text = Resources.S_Properties_of_user.Replace("<user>", user.CustomName);

         FAccount = user;
         FSettings = user.Settings;

         AssignPrivacy();
         AssignCapabilities();
         AssignUserInfo(user, true);

         checkBoxRememberPassword.Checked = FAccount.RememberPassword;
         checkBoxAutoLogon.Checked = FAccount.AutoLogon;
         comboBoxStartupStatus.SelectedValue = FSettings.StartupStatus;

         checkBoxLogonDelay.Checked = FSettings.LogonDelay > 0;
         comboBoxLogonDelay.Text = checkBoxLogonDelay.Checked ? FSettings.LogonDelay.ToString() : "";

         if (FSettings.AwayTimeout > 0)
         {
            checkBoxAwayTimeout.Checked = true;
            comboBoxAwayTimeout.Text = FSettings.AwayTimeout.ToString();
         }
         else if (Settings.Default.AwayTimeout > 0)
         {
            checkBoxAwayTimeout.Checked = FSettings.AwayTimeout < 0;
            comboBoxAwayTimeout.Text = Settings.Default.AwayTimeout.ToString();
         }
         else
         {
            checkBoxAwayTimeout.Checked = false;
            comboBoxAwayTimeout.Text = Settings.Default.Properties["AwayTimeout"].DefaultValue.ToString();
         }

         if (FSettings.NATimeout > 0)
         {
            checkBoxNaTimeout.Checked = true;
            comboBoxNaTimeout.Text = FSettings.NATimeout.ToString();
         }
         else if (Settings.Default.NATimeout > 0)
         {
            checkBoxNaTimeout.Checked = FSettings.NATimeout < 0;
            comboBoxNaTimeout.Text = Settings.Default.NATimeout.ToString();
         }
         else
         {
            checkBoxNaTimeout.Checked = false;
            comboBoxNaTimeout.Text = Settings.Default.Properties["NATimeout"].DefaultValue.ToString();
         }

         checkBoxOverrideCommonPrivacy.Checked =
            FSettings.UnknownUserMessageRule != PolicyRule.None ||
            FSettings.UnknownUserInvitationRule != PolicyRule.None ||
            FSettings.MyContactMessageRule != PolicyRule.None ||
            FSettings.MyContactInvitationRule != PolicyRule.None ||
            FSettings.VipContactInvitationRule != PolicyRule.None;

         labelEditConfigComment.Text = labelEditConfigComment.Text.Replace("<configName>", FAccount.ServiceConfig.ToString());

         buttonSave.Visible = true;
      }
      private void AssignUserInfo(Account user, bool summary)
      {
         labelSummaryCaption.Text = user.CustomName;

         SetupUserpic();

         textBoxCustomName.Text = user.CustomName;
         textBoxNickname.Text = user.Nickname;
         comboBoxLanguage.SelectedItem = user.Info.Language;
         comboBoxGender.SelectedItem = UserInfo.GetGenderAsString(user.Info.Gender, true);
         textBoxAbout.Text = user.Info.Description;

         labelLogin.Text = user.ServiceConfig.Service.LoginAlias + ":";
         textBoxLogin.Text = user.Login;
         textBoxEmail.Text = user.Info.Email;
         textBoxPhone.Text = user.Info.Phone;
         textBoxUrl.Text = user.Info.PersonalUrl;
         textBoxFullName.Text = user.Info.FullName;
         comboBoxCountry.Text = user.Info.Country;
         textBoxCity.Text = user.Info.City;

         int year = -1, month = -1, day = -1;
         DateTime? bd = user.Info.GetBirthdayAsDate(true, true, true);

         if (bd.HasValue)
         {
            year = bd.Value.Year;
            month = bd.Value.Month;
            day = bd.Value.Day;
         }
         else
         {
            year = month = day = -1;
         }

         comboBoxYear.Text = year > 0 ? year.ToString() : "";
         comboBoxMonth.SelectedIndex = month;
         comboBoxDay.SelectedIndex = day;

         textBoxWorkCity.Text = user.Info.Work.City;
         textBoxWorkAddress.Text = user.Info.Work.Address;
         comboBoxWorkCountry.Text = user.Info.Work.Country;
         textBoxDepartment.Text = user.Info.Work.Department;
         textBoxOrganization.Text = user.Info.Work.Organization;
         textBoxWorkPhone.Text = user.Info.Work.Phone;
         textBoxFax.Text = user.Info.Work.Fax;
         textBoxWorkUrl.Text = user.Info.Work.Url;
         textBoxWorkEmail.Text = user.Info.Work.Email;
         textBoxRole.Text = user.Info.Work.Role;

         if (summary) UserProperties.ComposeSummary(user, richTextBoxSummary, FFontU, FFontB);
      }

      private void buttonZoom_Click(object sender, EventArgs e)
      {
         UserProperties.ZoomUserpic(this, FAccount);
      }
      private void buttonSave_Click(object sender, EventArgs e)
      {
         Save();
      }
      private void buttonClose_Click(object sender, EventArgs e)
      {
         Close();
      }
      private void tabPageInfo_Click(object sender, EventArgs e)
      {
         tabPageInfo.Focus();
      }
      private void pictureBox1_Click(object sender, EventArgs e)
      {
         FCommunicator.ShowUserpicDialog();
      }
      private void window_SizeChanged(object sender, EventArgs e)
      {
         tabControl.Refresh();
      }
      private void buttonRefresh_Click(object sender, EventArgs e)
      {
         FCommunicator.LoadAccountData(FAccount);
      }
      private void pictureBox_MouseLeave(object sender, EventArgs e)
      {
         UserProperties.HideZoom();
      }
      private void textBoxPassword_Enter(object sender, EventArgs e)
      {
         if (textBoxPassword.Text == FDefaultPassword) textBoxPassword.Text = "";
      }
      private void textBoxPassword_Leave(object sender, EventArgs e)
      {
         if (checkBoxRememberPassword.Checked)
         {
            if (textBoxPassword.Text == "")
            {
               if (!string.IsNullOrEmpty(FAccount.Password)) textBoxPassword.Text = FDefaultPassword;
            }
         }
         else if (textBoxPassword.Text == FDefaultPassword)
         {
            textBoxPassword.Text = "";
         }
      }
      private void buttonEditConfig_Click(object sender, EventArgs e)
      {
         FAccount.ServiceConfig.Service.Driver.ShowDriverSettings(FAccount.ServiceConfig.ToString());
      }
      private void panelBottom_Paint(object sender, PaintEventArgs e)
      {
         if (!AeroGlassVisible) FCommunicator.DrawTheme(FCommunicator.ColorTheme, e.Graphics, (sender as Control).ClientRectangle, ColorThemeObject.PanelV);
      }
      private void buttonResetUserpic_Click(object sender, EventArgs e)
      {
         FCommunicator.ResetUserpic(FAccount);
      }
      private void panelInfoBody_Paint(object sender, PaintEventArgs e)
      {
         FCommunicator.DrawTheme(ColorTheme.Standard, e.Graphics, (sender as Control).ClientRectangle, ColorThemeObject.Pattern);
         //FCommunicator.DrawTheme(ColorTheme, e.Graphics, (sender as Control).ClientRectangle, ColorThemeObject.Area);
      }
      private void panelInfoHeader_Paint(object sender, PaintEventArgs e)
      {
         FCommunicator.DrawTheme(ColorTheme.Standard, e.Graphics, (sender as Control).ClientRectangle, ColorThemeObject.Pattern);
         //FCommunicator.DrawTheme(ColorTheme, e.Graphics, (sender as Control).ClientRectangle, ColorThemeObject.Pattern);
      }
      private void linkPrivacyDetails_Click(object sender, EventArgs e)
      {
         ControlEffects.Slide(panelContactsPolicy, SlideAction.Switch, true, e == null ? false : true, null, (action) =>
         {
            linkPrivacyDetails.Text = action == SlideAction.Collapse ?
                                      linkPrivacyDetails.Text.Replace("<<", ">>") :
                                      linkPrivacyDetails.Text.Replace(">>", "<<");
         });
      }
      private void buttonChangePassword_Click(object sender, EventArgs e)
      {
         panelPasswordSettingsMain.Visible = false;
         panelPasswordSettingsChangePassword.Visible = true;
         textBoxOldPassword.Select();
      }
      private void labelWorkInfoCaption_Click(object sender, EventArgs e)
      {
         tabPageInfo.Focus();
         ControlEffects.Slide(panelMiscInfo, SlideAction.Collapse, false);
         ControlEffects.Slide(panelPersonalInfo, SlideAction.Collapse, false);
         ControlEffects.Slide(panelWorkInfo, SlideAction.Switch, true);
      }
      private void labelMiscInfoCaption_Click(object sender, EventArgs e)
      {
         tabPageInfo.Focus();
         ControlEffects.Slide(panelPersonalInfo, SlideAction.Collapse, false);
         ControlEffects.Slide(panelWorkInfo, SlideAction.Collapse, true);
         ControlEffects.Slide(panelMiscInfo, SlideAction.Switch, true);
      }
      private void labelUseCommonSettings_Click(object sender, EventArgs e)
      {
         checkBoxAwayTimeout.Checked = Settings.Default.AwayTimeout > 0;
         comboBoxAwayTimeout.Text = Settings.Default.AwayTimeout > 0 ?
                                    Settings.Default.AwayTimeout.ToString() :
                                    Settings.Default.Properties["AwayTimeout"].DefaultValue.ToString();

         checkBoxNaTimeout.Checked = Settings.Default.NATimeout > 0;
         comboBoxNaTimeout.Text = Settings.Default.NATimeout > 0 ?
                                  Settings.Default.NATimeout.ToString() :
                                  Settings.Default.Properties["NATimeout"].DefaultValue.ToString();
      }
      private void labelCommonPrivacy_Click(object sender, EventArgs e)
      {
         FCommunicator.ShowSettings("Privacy");
      }
      private void window_AeroGlassEffectChanged(object sender, EventArgs e)
      {
         if (AeroGlassVisible)
         {
            buttonRefresh.Top = 10;
            buttonSave.Top = 10;
            buttonClose.Top = 10;
            panelSaving.Top = 12;
            buttonRefresh.Left = 4;
            buttonClose.Left = panelTab.Left + panelTab.Width - buttonClose.Width + 3;
         }
         else
         {
            buttonRefresh.Top = 7;
            buttonSave.Top = 7;
            buttonClose.Top = 7;
            panelSaving.Top = 9;
            buttonRefresh.Left = 6;
            buttonClose.Left = panelTab.Left + panelTab.Width - buttonClose.Width - 1;
         }
         buttonSave.Left = buttonClose.Left - buttonSave.Width - 6;
      }
      private void labelPersonalInfoCaption_Click(object sender, EventArgs e)
      {
         tabPageInfo.Focus();
         ControlEffects.Slide(panelWorkInfo, SlideAction.Collapse, false);
         ControlEffects.Slide(panelPersonalInfo, SlideAction.Switch, true);
      }
      private void buttonGoToVendorEditPage_Click(object sender, EventArgs e)
      {
         FAccount.ServiceConfig.Service.GoVendorPage(VendorPage.PersonalInfo);
      }
      private void checkBoxTimeout_CheckedChanged(object sender, EventArgs e)
      {
         if (sender == checkBoxLogonDelay)
         {
            comboBoxLogonDelay.Enabled = checkBoxLogonDelay.Checked;
            comboBoxLogonDelay.SelectedIndex = checkBoxLogonDelay.Checked ? 0 : -1;
         }
         else if (sender == checkBoxNaTimeout)
         {
            comboBoxNaTimeout.Enabled = checkBoxNaTimeout.Checked;
            comboBoxNaTimeout.Text = checkBoxNaTimeout.Checked ?
               Settings.Default.Properties["NATimeout"].DefaultValue.ToString() : "";
         }
         else if (sender == checkBoxAwayTimeout)
         {
            comboBoxAwayTimeout.Enabled = checkBoxAwayTimeout.Checked;
            comboBoxAwayTimeout.Text = checkBoxAwayTimeout.Checked ?
               Settings.Default.Properties["AwayTimeout"].DefaultValue.ToString() : "";
         }
      }
      private void tabControl_SelectedIndexChanged(object sender, EventArgs e)
      {
         if (tabControl.SelectedTab == tabPageSummary)
         {
            buttonSave.Visible = false;
         }
         else
         {
            buttonSave.Visible = true;
         }
      }
      private void richTextBoxSummary_MouseUp(object sender, MouseEventArgs e)
      {
         if (e.Button == MouseButtons.Right) Window.ShowStandardTextMenu(richTextBoxSummary);
      }
      private void buttonCancelChangePassword_Click(object sender, EventArgs e)
      {
         panelPasswordSettingsChangePassword.Visible = false;
         panelPasswordSettingsMain.Visible = true;
      }
      private void panelHeader_MouseUpDown(object sender, MouseEventArgs e)
      {
         Label label = sender is Label ? sender as Label : (sender as Control).Controls[1] as Label;
         
         label.ForeColor = label.ForeColor == labelSummaryCaption.ForeColor ? Color.SteelBlue : labelSummaryCaption.ForeColor;
      }
      private void labelPasswordSettingsCaption_Click(object sender, EventArgs e)
      {
         tabPagePrivacy.Focus();
         if (panelContactsPolicy.Height > 300) linkPrivacyDetails_Click(this, null);
         ControlEffects.Slide(panelPasswordSettings, SlideAction.Switch, true);
      }
      private void richTextBoxSummary_LinkClicked(object sender, LinkClickedEventArgs e)
      {
         Shell.OpenLink(e.LinkText, "");
      }
      private void checkBoxOverrideCommonPrivacy_CheckedChanged(object sender, EventArgs e)
      {
         if (checkBoxOverrideCommonPrivacy.Checked)
         {
            linkPrivacyDetails.Visible = true;
            checkBoxMessageRuleBlock.Visible = true;
            checkBoxInvitationRuleBlock.Visible = true;
            linkPrivacyDetails.Text = linkPrivacyDetails.Text.Replace("<<", ">>");

            checkBoxOverrideCommonPrivacy.Top = 25;

            if (FSettings.UnknownUserMessageRule == PolicyRule.None)
                FSettings.UnknownUserMessageRule = Settings.Default.UnknownUserMessageRule;

            if (FSettings.UnknownUserInvitationRule == PolicyRule.None)
                FSettings.UnknownUserInvitationRule = Settings.Default.UnknownUserInvitationRule;

            AssignPrivacy();
         }
         else
         {
            linkPrivacyDetails.Visible = false;
            checkBoxMessageRuleBlock.Visible = false;
            checkBoxInvitationRuleBlock.Visible = false;

            checkBoxOverrideCommonPrivacy.Top = panelContactsPolicyBasics.Height / 2 - 10;

            if (panelContactsPolicy.Height > 300) linkPrivacyDetails_Click(this, null);
         }
      }
      private void checkBoxMessageRuleBlock_CheckedChanged(object sender, EventArgs e)
      {
         if (FAssigningPrivacy) return;

         FSettings.UnknownUserMessageRule = checkBoxMessageRuleBlock.Checked ? PolicyRule.Block : PolicyRule.Allow;
         if (checkBoxMessageRuleBlock.Checked) FSettings.UnknownUserInvitationRule = PolicyRule.Block;

         AssignPrivacy();
      }
      private void checkBoxInvitationRuleBlock_CheckedChanged(object sender, EventArgs e)
      {
         if (FAssigningPrivacy) return;

         FSettings.UnknownUserInvitationRule = checkBoxInvitationRuleBlock.Checked ? PolicyRule.Block : PolicyRule.Ask;
         //if (checkBoxInvitationRuleBlock.Checked) FSettings.UnknownUserMessageRule = PolicyRule.Block;

         AssignPrivacy();
      }
      private void comboBoxUnknownUserMessageRule_SelectedIndexChanged(object sender, EventArgs e)
      {
         if (FAssigningPrivacy || comboBoxUnknownUserMessageRule.SelectedValue == null) return;

         FSettings.UnknownUserMessageRule = (PolicyRule)Enum.Parse(typeof(PolicyRule), (string)comboBoxUnknownUserMessageRule.SelectedValue);

         AssignPrivacy();
      }
      private void comboBoxUnknownUserInvitationRule_SelectedIndexChanged(object sender, EventArgs e)
      {
         if (FAssigningPrivacy || comboBoxUnknownUserInvitationRule.SelectedValue == null) return;

         FSettings.UnknownUserInvitationRule = (PolicyRule)Enum.Parse(typeof(PolicyRule), (string)comboBoxUnknownUserInvitationRule.SelectedValue);

         AssignPrivacy();
      }
      private void comboBoxMyContactsMessageRule_SelectedIndexChanged(object sender, EventArgs e)
      {
         if (FAssigningPrivacy || comboBoxMyContactsMessageRule.SelectedValue == null) return;

         FSettings.MyContactMessageRule = (PolicyRule)Enum.Parse(typeof(PolicyRule), (string)comboBoxMyContactsMessageRule.SelectedValue);
      }
      private void comboBoxMyContactsInvitationRule_SelectedIndexChanged(object sender, EventArgs e)
      {
         if (FAssigningPrivacy || comboBoxMyContactsInvitationRule.SelectedValue == null) return;

         FSettings.MyContactInvitationRule = (PolicyRule)Enum.Parse(typeof(PolicyRule), (string)comboBoxMyContactsInvitationRule.SelectedValue);
      }
      private void comboBoxVipInvitationRule_SelectedIndexChanged(object sender, EventArgs e)
      {
         if (FAssigningPrivacy || comboBoxVipInvitationRule.SelectedValue == null) return;

         FSettings.VipContactInvitationRule = (PolicyRule)Enum.Parse(typeof(PolicyRule), (string)comboBoxVipInvitationRule.SelectedValue);
      }
      private void communicator_PropertyChanged(object sender, PropertyChangedEventArgs e)
      {
         if (e.PropertyName == "ColorTheme") ColorTheme = FCommunicator.ColorTheme;
         else if (e.PropertyName == "RenderMode") RenderMode = FCommunicator.RenderMode;
         else if (e.PropertyName == "Userpic") SetupUserpic();
      }
      private void communicator_LoadAccountDataState(object sender, NetworkOperationEventArgs e)
      {
         if (e.Error == null && e.State == OperationState.Completed)
         {
            if (FAccount == e.Operation.Account) AssignUser(e.Operation.Account);
         }
      }
      private void communicator_SaveAccountDataState(object sender, NetworkOperationEventArgs e)
      {
         if (e.Error != null)
         {
            buttonSave.Enabled = true;
            if (e.Error.ReasonCode != ErrorReasonCode.ConnectionRequired &&
                e.Error.ReasonCode != ErrorReasonCode.NotSupported) FCommunicator.ShowError(Resources.S_Request_info_error.Replace("<user>", FAccount.CustomName), e.Error);
         }
         else if (e.State == OperationState.Completed)
         {
            buttonSave.Enabled = true;
            AssignUserInfo(FAccount, true);
         }
         else if (e.State == OperationState.DataSent)
         {
            buttonSave.Enabled = false;
         }
      }
      private void communicator_RequestUserInfoState(object sender, NetworkOperationEventArgs e)
      {
         if (e.GetParam("User", null) != FAccount) return;

         User user = (User)e.GetResult("User", null);

         if (e.Error != null)
         {
            buttonRefresh.Enabled = true;
            if (e.Error.ReasonCode != ErrorReasonCode.ConnectionRequired) FCommunicator.ShowError(Resources.S_Request_info_error.Replace("<user>", FAccount.CustomName), e.Error);
         }
         else if (e.State == OperationState.Completed)
         {
            if (user == null)
            {
               MessageBox.Show(Resources.S_User_does_not_exist.Replace("<id>", FAccount.Identifier), Text, MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            }
            else
            {
               buttonRefresh.Enabled = true;
               AssignUserInfo(FAccount, true);
            }
         }
         else
         {
            buttonRefresh.Enabled = false;
         }
      }
   }
}
